#!/usr/bin/python

# pip install aliyun-python-sdk-core
import urllib.parse
import oss2
from .base import BaseStorage


class AliOss(BaseStorage):

    def setup(self, key_id=None, secret=None, host=None, bucket=None, root_dir='hss', cdn=None, region=None):
        auth = oss2.Auth(key_id, secret)
        self.bucket = oss2.Bucket(auth, host, bucket)
        host = host.split('://', 1)[-1]
        self.host = cdn if cdn else f'https://{bucket}.{host}/'
        self.root = root_dir.strip('/')
        self.bucket_host = f'https://{bucket}.{host}/'

    def object_exists(self, path: str) -> bool:
        path = self.parse_path(path)
        exist = self.bucket.object_exists(path)
        return exist

    def parse_path(self, path):
        if path.startswith('/'):
            return f'{self.root}{path}'
        else:
            return f'{self.root}/{path}'

    def upload(self, path, data, mode=BaseStorage.Write, expire: int = None):
        """
        @params path: 上传到云端的文件名
        @params data: 上传数据，需要二进制
        @params mode: 写模式 Write/Append
        @params expire: 过期时间单位 s
        """
        path = self.parse_path(path)
        print(f'path is {path}')
        if mode == BaseStorage.Append:
            result = self.bucket.head_object(path)
            self.bucket.append_object(path, result.content_length, data)
        else:
            self.bucket.put_object(path, data)

    def download_url(self, file_path):
        """
        @params path: 上传到云端的文件名
        """
        return self.host + urllib.parse.quote(self.parse_path(file_path))

    def delete(self, path):
        path = self.parse_path(path)
        self.bucket.delete_object(path)

    def image_resize(self, path, scale):
        scale = int(scale * 100)
        if scale < 1:
            scale = 1
        if scale > 1000:
            scale = 1000
        return f'{path}?x-oss-process=image/resize,p_{scale}', None

    def get_file_meta(self, path):
        """
        获取文件元信息
        :param path:
        :return: head.last_modified, head.content_type, head.content_length

        head.last_modified: 文件最后修改时间戳，类型为int，可能是None
        head.content_type: 文件的MIME类型，可能是None
        head.content_length(bytes): Content-Length，可能是None
        """
        path = self.parse_path(path)
        head = self.bucket.head_object(path)
        return head.last_modified, head.content_type, head.content_length

    def list_dir_files(self, path: str, max_keys=100) -> list:
        """
        获取目录下的所有文件
        """
        keys = []
        for obj in oss2.ObjectIterator(bucket=self.bucket, prefix=path, max_keys=max_keys):
            keys.append(obj.key)
        return keys


if __name__ == '__main__':
    pass
    # def demo():
    #     config = {"key_id": "LTAI5tHKtTwNumoUxZ1psoz6",
    #               "secret": "UfAT5oAk6xYHYIas3hiIT5kUfaOgNe",
    #               "bucket": "qy829",  # 桶名
    #               "region": "cn-nanjing",
    #               "host": "https://oss-cn-nanjing.aliyuncs.com",
    #               }
    #     oss = AliOss(**config)
    #     print(oss.list_dir_files("hss"))
    #     path = '寒山寺hhh.xls'
    #
    #     with open("./aaaa.xls", 'rb') as f:
    #         oss.upload(path, f)
    #
    #     print(oss.download_url(path))
    #
    #
    # demo()

    # oss = AliOss(**settings.STORAGE_OPTIONS[1]['args'])
    # print(oss)
